/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.discovery;

import java.util.ArrayList;
import java.util.List;

import mosdi.discovery.MotifFinder.SearchState;

public class MatchCountSearch implements MotifFinder.SearchSpecification {
	private int[] occurrenceCountAnnotation;
	private int[] maxMatchCountAnnotation;
	private int threshold;
	private SearchState state;
	private List<EvaluatedPattern> results;
	
	/** Constructor.
	 * @param maxMatchCountAnnotation May be null.
	 */
	public MatchCountSearch(int threshold, int[] occurrenceCountAnnotation, int[] maxMatchCountAnnotation) {
		this.threshold = threshold;
		this.occurrenceCountAnnotation = occurrenceCountAnnotation;
		this.maxMatchCountAnnotation = maxMatchCountAnnotation;
	}
	
	@Override
	public void initialize(SearchState searchState) {
		this.state = searchState;
		if (maxMatchCountAnnotation!=null) state.requestMultiplicity();
		this.results = new ArrayList<EvaluatedPattern>();
	}
	
	@Override
	public void updatePattern(int newCharacter, int leftmostChangedPosition) { }

	@Override
	public boolean check(int prefixLength, int[] nodes) {
		int matches = 0;
		for (int node : nodes) {
			if (maxMatchCountAnnotation==null) {
				matches+=occurrenceCountAnnotation[node];
			} else {
				matches+=Math.min(occurrenceCountAnnotation[node], maxMatchCountAnnotation[node]*state.getMultiplicityLeft());
			}
			if (matches>=threshold) return true;
		}
		return false;
	}

	@Override
	public void evaluateCandidate(int[] nodes) {
		int matches = 0;
		for (int node : nodes) matches+=occurrenceCountAnnotation[node];
		if (matches>=threshold) results.add(new EvaluatedPattern(state.getPattern(), matches));
	}

	public List<EvaluatedPattern> getResults() { return results; }
}
